import { deleteResume, getResume } from "~/server/database/services/resumeService";
import authMiddleware from "~/server/middleware/auth";

export default defineEventHandler(async (event) => {
  try {
    // 使用认证中间件获取用户信息
    await authMiddleware(event);
    
    const id = getRouterParam(event, "id");
    
    // 从event.context中获取用户信息
    const user = event.context.user;

    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: "简历ID是必需的"
      });
    }

    // 检查简历是否存在
    const existingResume = await getResume(parseInt(id));
    if (!existingResume) {
      throw createError({
        statusCode: 404,
        statusMessage: "简历不存在"
      });
    }
    
    // 检查简历是否属于当前用户
    if (existingResume.userId !== user.id) {
      throw createError({
        statusCode: 403,
        statusMessage: "无权删除此简历"
      });
    }

    const result = await deleteResume(parseInt(id));
    
    return {
      success: true,
      data: result,
      message: "简历删除成功"
    };
  } catch (error: any) {
    console.error("删除简历失败:", error);
    if (error.statusCode) {
      throw error;
    }
    throw createError({
      statusCode: 500,
      statusMessage: "删除简历失败"
    });
  }
});
